<template>
  <div class="page-container">
    <!-- 头部 -->
    <div class="header">
      <button class="back-btn" @click="goBack">
        <i class="fas fa-arrow-left"></i>
      </button>
      <h1 class="title">{{ taskData.title || "心理训练任务练习学习页面" }}</h1>
      <div class="placeholder"></div>
    </div>

    <!-- 主要内容 -->
    <div class="main-content">
      <!-- 视频学习部分 -->
      <div v-if="taskData.type === 1" class="card video-card">
        <div class="card-header">
          <div class="icon-wrapper video-icon">
            <i class="fas fa-video"></i>
          </div>
          <h2>视频学习</h2>
        </div>

        <div class="video-container">
          <video
            v-if="taskData.url && isVideoUrlValid"
            ref="videoPlayer"
            :src="taskData.url"
            controls
            class="video-player"
            @timeupdate="updateVideoProgress"
            @loadedmetadata="onVideoLoaded"
            @error="onVideoError"
            @play="onVideoPlay"
            @pause="onVideoPause"
            preload="metadata"
            playsinline
            webkit-playsinline
          >
            您的浏览器不支持视频播放。
          </video>
          <div v-else-if="!taskData.url" class="no-content">
            <i class="fas fa-video-slash"></i>
            <p>暂无视频内容</p>
          </div>
          <div v-else class="no-content">
            <i class="fas fa-exclamation-triangle"></i>
            <p>视频加载失败，请检查视频地址</p>
            <button @click="retryVideoLoad" class="retry-btn">重试</button>
          </div>
        </div>

        <div class="video-info">
          <h3 class="video-title">{{ taskData.title || "视频训练" }}</h3>
          <p class="video-description">
            {{ taskData.description || "请认真观看视频内容，完成训练任务。" }}
          </p>
        </div>

        <div class="video-controls">
          <button
            class="play-btn"
            @click="toggleVideoPlay"
            :disabled="!isVideoUrlValid"
          >
            <i :class="isVideoPlaying ? 'fas fa-pause' : 'fas fa-play'"></i>
          </button>
          <div class="progress-container">
            <div class="progress-bar">
              <div
                class="progress-fill"
                :style="{ width: videoProgress + '%' }"
              ></div>
            </div>
          </div>
          <span class="time-display">{{ currentTime }} / {{ duration }}</span>
        </div>
      </div>

      <!-- 音频学习部分 -->
      <div v-if="taskData.type === 2" class="card audio-card">
        <div class="card-header">
          <div class="icon-wrapper audio-icon">
            <i class="fas fa-music"></i>
          </div>
          <h2>音频练习</h2>
        </div>

        <div class="audio-list">
          <div class="audio-item" @click="playAudio">
            <div class="audio-icon-wrapper">
              <i :class="isAudioPlaying ? 'fas fa-pause' : 'fas fa-play'"></i>
            </div>
            <div class="audio-info">
              <h3 class="audio-title">{{ taskData.title || "音频训练" }}</h3>
              <p class="audio-duration">{{ audioDuration }}</p>
            </div>
            <i class="fas fa-chevron-right arrow-icon"></i>
          </div>
        </div>

        <!-- 音频播放进度 -->
        <div v-if="taskData.url" class="audio-controls">
          <div class="progress-container">
            <div class="progress-bar">
              <div
                class="progress-fill"
                :style="{ width: audioProgress + '%' }"
              ></div>
            </div>
          </div>
          <span class="time-display"
            >{{ audioCurrentTime }} / {{ audioDuration }}</span
          >
        </div>

        <div v-if="!taskData.url" class="no-content">
          <i class="fas fa-music-slash"></i>
          <p>暂无音频内容</p>
        </div>
      </div>

      <!-- 文本学习部分 -->
      <div v-if="taskData.type === 3" class="card text-card">
        <div class="card-header">
          <div class="icon-wrapper text-icon">
            <i class="fas fa-file-alt"></i>
          </div>
          <h2>文本学习</h2>
        </div>

        <div class="text-content">
          <h3 class="text-title">{{ taskData.title || "文本训练" }}</h3>
          <div
            class="text-body"
            v-html="taskData.content || taskData.description || '暂无文本内容'"
          ></div>
        </div>
      </div>

      <!-- 训练说明 -->
      <div class="card info-card">
        <div class="card-header">
          <div class="icon-wrapper info-icon">
            <i class="fas fa-info-circle"></i>
          </div>
          <h2>训练说明</h2>
        </div>

        <div class="info-list">
          <p>1. 选择一个安静舒适的环境进行训练</p>
          <p>2. 建议每天固定时间练习，形成习惯</p>
          <p>3. 训练过程中保持专注，避免干扰</p>
          <p>4. 完成训练后可以记录自己的感受</p>
          <p v-if="taskData.note" class="task-note">
            备注：{{ taskData.note }}
          </p>
        </div>
      </div>
    </div>

    <!-- 底部操作按钮 -->
    <div class="footer">
      <button class="action-btn" @click="showConfirmDialog">
        <i class="fas fa-check-circle"></i>
        完成训练
      </button>
      <button class="retry-btn2" @click="gohome()">返回首页</button>
    </div>

    <!-- 确认对话框 -->
    <div
      v-if="showConfirmDialogVisible"
      class="modal-overlay"
      @click.self="hideConfirmDialog"
    >
      <div class="modal-content confirm-modal">
        <h3 class="confirm-title">确定要结束本次训练吗？</h3>
        <p class="confirm-message">完成训练后系统将记录您的训练进度</p>

        <div class="confirm-buttons">
          <button class="cancel-btn" @click="hideConfirmDialog">取消</button>
          <button class="confirm-btn" @click="completeTraining">
            确定完成
          </button>
        </div>
      </div>
    </div>

    <!-- 提示消息 -->
    <div v-if="showToast" class="toast" :class="{ 'toast-error': isError }">
      {{ toastMessage }}
    </div>
  </div>
</template>

<script>
import { practiceCheckin } from "@/api/user";

export default {
  name: "MentalTrainingPage",
  data() {
    return {
      taskData: {},
      showConfirmDialogVisible: false,
      showToast: false,
      toastMessage: "",
      isError: false,

      // 视频相关
      isVideoPlaying: false,
      videoProgress: 0,
      currentTime: "00:00",
      duration: "00:00",
      isVideoUrlValid: true,
      videoLoadAttempts: 0,

      // 音频相关
      isAudioPlaying: false,
      audioProgress: 0,
      audioCurrentTime: "00:00",
      audioDuration: "00:00",
      audioPlayer: null,
    };
  },
  created() {
    this.parseTaskData();
    this.initAudioPlayer();
    this.validateVideoUrl();
  },
  beforeDestroy() {
    // 清理音频播放器
    if (this.audioPlayer) {
      this.audioPlayer.pause();
      this.audioPlayer = null;
    }
  },
  methods: {
    gohome() {
      this.$router.go(-2);
    },
    parseTaskData() {
      try {
        if (this.$route.query.task) {
          this.taskData = JSON.parse(this.$route.query.task);
          console.log("任务数据:", this.taskData);
          // 验证视频URL
          if (this.taskData.type === 1) {
            this.validateVideoUrl();
          }
        }
      } catch (error) {
        console.error("解析任务数据失败:", error);
        this.showToastMessage("数据加载失败，请返回重试", true);
      }
    },

    validateVideoUrl() {
      if (this.taskData.type === 1 && this.taskData.url) {
        // 简单的URL验证
        const video = document.createElement("video");
        video.src = this.taskData.url;
        video.preload = "metadata";

        video.onloadedmetadata = () => {
          this.isVideoUrlValid = true;
          console.log("视频URL有效，时长:", video.duration);
        };

        video.onerror = () => {
          this.isVideoUrlValid = false;
          console.error("视频URL无效或无法加载");
        };

        // 设置超时检查
        setTimeout(() => {
          if (!this.isVideoUrlValid && this.videoLoadAttempts < 3) {
            this.videoLoadAttempts++;
            this.validateVideoUrl(); // 重试
          }
        }, 3000);
      }
    },

    initAudioPlayer() {
      if (this.taskData.type === 2 && this.taskData.url) {
        this.audioPlayer = new Audio(this.taskData.url);
        this.audioPlayer.addEventListener("loadedmetadata", () => {
          this.audioDuration = this.formatTime(this.audioPlayer.duration);
        });
        this.audioPlayer.addEventListener(
          "timeupdate",
          this.updateAudioProgress
        );
        this.audioPlayer.addEventListener("ended", () => {
          this.isAudioPlaying = false;
          this.audioProgress = 100;
        });
      }
    },

    goBack() {
      this.$router.go(-1);
    },

    // 视频控制方法
    toggleVideoPlay() {
      const video = this.$refs.videoPlayer;
      if (!video || !this.isVideoUrlValid) return;

      try {
        if (this.isVideoPlaying) {
          video.pause();
        } else {
          video.play().catch((error) => {
            console.error("播放失败:", error);
            this.showToastMessage("视频播放失败，请检查网络或视频文件", true);
          });
        }
      } catch (error) {
        console.error("视频控制错误:", error);
        this.showToastMessage("视频控制出错", true);
      }
    },

    onVideoPlay() {
      this.isVideoPlaying = true;
    },

    onVideoPause() {
      this.isVideoPlaying = false;
    },

    onVideoLoaded() {
      const video = this.$refs.videoPlayer;
      if (video) {
        this.duration = this.formatTime(video.duration);
        this.isVideoUrlValid = true;
        console.log("视频加载完成，时长:", video.duration);
      }
    },

    onVideoError(event) {
      console.error("视频加载错误:", event);
      this.isVideoUrlValid = false;
      this.showToastMessage("视频加载失败，请检查视频地址", true);
    },

    retryVideoLoad() {
      this.videoLoadAttempts = 0;
      this.isVideoUrlValid = true;
      this.$nextTick(() => {
        this.validateVideoUrl();
      });
    },

    updateVideoProgress() {
      const video = this.$refs.videoPlayer;
      if (video && video.duration) {
        this.videoProgress = (video.currentTime / video.duration) * 100;
        this.currentTime = this.formatTime(video.currentTime);
      }
    },

    // 音频控制方法
    playAudio() {
      if (!this.audioPlayer) return;

      if (this.isAudioPlaying) {
        this.audioPlayer.pause();
      } else {
        this.audioPlayer.play().catch((error) => {
          console.error("音频播放失败:", error);
          this.showToastMessage("音频播放失败", true);
        });
      }
      this.isAudioPlaying = !this.isAudioPlaying;
    },

    updateAudioProgress() {
      if (this.audioPlayer && this.audioPlayer.duration) {
        this.audioProgress =
          (this.audioPlayer.currentTime / this.audioPlayer.duration) * 100;
        this.audioCurrentTime = this.formatTime(this.audioPlayer.currentTime);
      }
    },

    // 时间格式化
    formatTime(seconds) {
      if (!seconds || isNaN(seconds)) return "00:00";

      const mins = Math.floor(seconds / 60);
      const secs = Math.floor(seconds % 60);
      return `${mins.toString().padStart(2, "0")}:${secs
        .toString()
        .padStart(2, "0")}`;
    },

    showConfirmDialog() {
      this.showConfirmDialogVisible = true;
    },

    hideConfirmDialog() {
      this.showConfirmDialogVisible = false;
    },

    completeTraining() {
      this.hideConfirmDialog();

      // 构建请求数据
      let data = {
        personalPracticeId: this.taskData.id,
        practiceTime: this.taskData.practiceTime,
        userId: localStorage.getItem("userId"),
      };
      practiceCheckin(data)
        .then((res) => {
          if (res.code === 200) {
            this.showToastMessage("训练已完成！");
            setTimeout(() => {
              this.$router.go(-1);
            }, 1500);
          } else {
            this.showToastMessage(res.message || "完成训练失败，请重试", true);
          }
        })
        .catch((error) => {
          console.error("获取数据失败:", error);
        });
    },

    getCurrentProgress() {
      // 根据不同类型返回进度
      switch (this.taskData.type) {
        case 1: // 视频
          return Math.floor(this.videoProgress);
        case 2: // 音频
          return Math.floor(this.audioProgress);
        case 3: // 文本
          return 100; // 文本直接完成
        default:
          return 100;
      }
    },

    showToastMessage(message, isError = false) {
      this.toastMessage = message;
      this.isError = isError;
      this.showToast = true;

      setTimeout(() => {
        this.showToast = false;
        this.isError = false;
      }, 3000);
    },
  },
};
</script>

<style scoped>
.video-container {
  position: relative;
  width: 100%;
  height: 0;
  padding-bottom: 56.25%; /* 16:9 Aspect Ratio */
  background: #000;
  border-radius: 12px;
  margin-bottom: 16px;
  overflow: hidden;
}

.video-player {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border-radius: 12px;
  object-fit: contain;
}

.retry-btn {
  background-color: #3b82f6;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 8px;
  margin-top: 12px;
  cursor: pointer;
  font-size: 14px;
}

.retry-btn:hover {
  background-color: #2563eb;
}

/* 禁用状态样式 */
.play-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 文本卡片样式 */
.text-card .text-content {
  padding: 16px 0;
}

.text-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 12px;
  color: #1a233d;
}

.text-body {
  color: #374151;
  line-height: 1.8;
  font-size: 14px;
}

/* 视频播放器样式 */
.video-player {
  width: 100%;
  height: 100%;
  border-radius: 12px;
  background: #000;
}

/* 音频控制样式 */
.audio-controls {
  margin-top: 16px;
  padding: 0 16px;
}

/* 无内容提示样式 */
.no-content {
  text-align: center;
  padding: 40px 20px;
  color: #9ca3af;
}

.no-content i {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.5;
}

.no-content p {
  margin: 0;
  font-size: 14px;
}

/* 文本图标样式 */
.text-icon {
  background-color: #fef3c7;
  color: #f59e0b;
}

/* 任务备注样式 */
.task-note {
  color: #ef4444;
  font-weight: 500;
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #e5e7eb;
}

/* 错误提示样式 */
.toast-error {
  background-color: #ef4444 !important;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .header {
    padding: 16px 12px;
  }

  .title {
    font-size: 18px;
  }

  .card {
    padding: 16px;
    margin-bottom: 16px;
  }

  .footer {
    padding: 12px 16px;
  }
}

.page-container {
  font-family: "Noto Sans SC", sans-serif;
  background: linear-gradient(135deg, #f9faff 0%, #f5f7ff 100%);
  color: #1a233d;
  line-height: 1.6;
}

.container {
  max-width: 600px;
  margin: 0 auto;
  padding: 0 16px;
  box-sizing: border-box;
}

/* 头部样式 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24px 16px;
  box-sizing: border-box;
  background-color: white;
  position: sticky;
  top: 0;
  z-index: 50;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.back-btn {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #eef0ff;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #5b67ff;
  border: none;
  cursor: pointer;
}

.title {
  font-size: 20px;
  font-weight: 600;
  color: #374151;
  margin: 0;
}

.placeholder {
  width: 36px;
}

/* 卡片通用样式 */
.card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 6px 20px rgba(134, 151, 206, 0.15);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  margin-bottom: 24px;
  padding: 24px;
  box-sizing: border-box;
}

.card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 25px rgba(134, 151, 206, 0.2);
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}

.icon-wrapper {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
}

.video-icon {
  background-color: #dbeafe;
  color: #3b82f6;
}

.audio-icon {
  background-color: #f3e8ff;
  color: #8b5cf6;
}

.info-icon {
  background-color: #dcfce7;
  color: #22c55e;
}

.card-header h2 {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

/* 视频部分样式 */
.video-container {
  position: relative;
  padding-bottom: 56.25%; /* 16:9 Aspect Ratio */
  box-sizing: border-box;
  height: 0;
  overflow: hidden;
  border-radius: 12px;
  margin-bottom: 16px;
}

.video-container iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border: none;
}

.video-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 8px;
}

.video-description {
  color: #6b7280;
  margin-bottom: 16px;
}

.video-controls {
  display: flex;
  align-items: center;
  gap: 16px;
}

.play-btn {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #ebf4ff;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #3b82f6;
  border: none;
  cursor: pointer;
}

.progress-container {
  flex: 1;
}

.progress-bar {
  height: 4px;
  background: rgba(91, 103, 255, 0.3);
  border-radius: 2px;
}

.progress-fill {
  height: 100%;
  background: #5b67ff;
  border-radius: 2px;
}

.time-display {
  font-size: 14px;
  color: #6b7280;
}

/* 音频部分样式 */
.audio-item {
  background: #eef0ff;
  padding: 16px;
  box-sizing: border-box;
  border-radius: 12px;
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.audio-item:hover {
  background: #e0e4ff;
  transform: translateX(5px);
}

.audio-icon-wrapper {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background-color: #3b82f6;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  margin-right: 16px;
}

.audio-info {
  flex: 1;
}

.audio-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 4px;
}

.audio-duration {
  font-size: 14px;
  color: #6b7280;
  margin: 0;
}

.arrow-icon {
  color: #9ca3af;
}

/* 训练说明部分样式 */
.info-list p {
  color: #374151;
  margin-bottom: 8px;
}

/* 底部按钮样式 */
.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px 24px;
  box-sizing: border-box;
  display: flex;
  justify-content: space-around;
}

.action-btn {
  background-color: #10b981;
  color: white;
  padding: 12px 32px;
  box-sizing: border-box;
  border-radius: 50px;
  font-weight: 600;
  display: flex;
  align-items: center;
  border: none;
  cursor: pointer;
  box-shadow: 0 6px 18px rgba(72, 213, 151, 0.3);
  transition: all 0.3s ease;
}

.action-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 25px rgba(72, 213, 151, 0.4);
}

.action-btn i {
  margin-right: 8px;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;
  animation: fadeIn 0.3s;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.audio-modal {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-sizing: border-box;
  width: 90%;
  max-width: 400px;
  position: relative;
}

.close-btn {
  position: absolute;
  top: 16px;
  right: 16px;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: #f3f4f6;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #6b7280;
  border: none;
  cursor: pointer;
}

.modal-header {
  text-align: center;
  margin-bottom: 24px;
}

.modal-title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 4px;
}

.modal-duration {
  color: #6b7280;
  margin: 0;
}

.modal-body {
  display: flex;
  justify-content: center;
  margin-bottom: 24px;
}

.audio-icon-large {
  width: 96px;
  height: 96px;
  border-radius: 50%;
  background-color: #ebf4ff;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #3b82f6;
  font-size: 24px;
}

.modal-controls {
  display: flex;
  align-items: center;
  gap: 16px;
}

.modal-play-btn {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background-color: #3b82f6;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  border: none;
  cursor: pointer;
}

/* 确认对话框样式 */
.confirm-modal {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-sizing: border-box;
  max-width: 400px;
  text-align: center;
}

.confirm-title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 16px;
}

.confirm-message {
  color: #6b7280;
  margin-bottom: 24px;
}

.confirm-buttons {
  display: flex;
  justify-content: center;
  gap: 16px;
}

.cancel-btn,
.confirm-btn {
  padding: 8px 24px;
  box-sizing: border-box;
  border-radius: 12px;
  font-weight: 500;
  border: none;
  cursor: pointer;
}

.cancel-btn {
  background-color: #f3f4f6;
  color: #374151;
}

.confirm-btn {
  background-color: #10b981;
  color: white;
}

/* 提示消息样式 */
.toast {
  position: fixed;
  top: 24px;
  left: 50%;
  transform: translateX(-50%);
  background-color: #10b981;
  color: white;
  padding: 12px 24px;
  box-sizing: border-box;
  border-radius: 9999px;
  font-weight: 500;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
  animation: slideIn 0.3s;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translate(-50%, -20px);
  }
  to {
    opacity: 1;
    transform: translate(-50%, 0);
  }
}
.retry-btn2 {
  background: #40a2f4;

  color: white;
  border: none;
  padding: 12px 30px;
  border-radius: 25px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}
</style>
